import { PageContainer, ProTable } from "@ant-design/pro-components";
import {
  Button,
  Modal,
  Input,
  Form,
  Space,
  Image,
  message,
  Popconfirm,
  Select,
} from "antd";
import { connect } from "umi";
import { namespace, calcColumns } from "./configFile";
import { useEffect, useRef, useState } from "react";
import { DeleteOutlined, PlusOutlined } from "@ant-design/icons";
import UploadPreview from "@/components/UploadPreview";
import styles from "./styles.less";
import Https from "@/utils/Https";
const Page = (props) => {
  const { dispatch, submitLoading } = props;
  const [open, setOpen] = useState(false);
  const [postImg, setPostImg] = useState("");
  const [titleType, setTitleType] = useState(0);
  const actionRef = useRef();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  // useEffect(() => {
  //   dispatch({
  //     type: `${namespace}/pageInit`,
  //   });
  // }, []);

  const toggleState = (params) => {
    dispatch({
      type: `${namespace}/toggleState`,
      params,
      callback: () => {
        actionRef.current?.reload();
      },
    });
  };
  const editInfo = (params) => {
    setTitleType(1);
    form.setFieldsValue({
      ...params,
      imgUrl: params.imgUrl,
    });
    setPostImg(params.imgUrl);
    setOpen(true);
  };

  const operate = {
    title: "操作",
    fixed: "right",
    dataIndex: "operator",
    align: "center",
    hideInSearch: true,
    render: (_, record) => {
      const { status, id } = record;
      return (
        <Space>
          <Button type="link" onClick={() => editInfo(record)}>
            编辑
          </Button>
          {status == 1 ? (
            <Popconfirm
              title="是否确定下架?"
              onConfirm={() => toggleState({ id, status: false })}
            >
              <Button type="link" danger>
                下架
              </Button>
            </Popconfirm>
          ) : (
            <Button
              type="link"
              onClick={() => toggleState({ id, status: true })}
            >
              上架
            </Button>
          )}
        </Space>
      );
    },
  };
  const getList = async (params) => {
    setLoading(true);
    let res: any = await Https.post("/selling/poster/list", params, true);
    setLoading(false);
    let records = [];
    let total = 0;
    if (res.code == 200 && res.data) {
      records = res.data.records;
      total = res.data.total;
    } else {
      message.error(res.msg);
    }
    return { success: true, data: records, total };
  };
  const submitForm = async () => {
    const res = await form.validateFields();
    let url = res.id ? "/selling/poster/update" : "/selling/poster/add";
    let params = {
      ...res,
      imgUrl: postImg,
    };
    setLoading(true);
    let result: any = await Https.post(url, params, true);
    setLoading(false);
    if (result.code == 200) {
      message.success("保存成功");
      setOpen(false);
      actionRef.current && actionRef.current?.reload();
    } else {
      message.error(result.msg);
    }
  };
  return (
    <PageContainer>
      <ProTable
        search={false}
        actionRef={actionRef}
        toolBarRender={() => [
          <Button
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              setTitleType(0);
              form.resetFields();
              setPostImg("");
              setOpen(true);
            }}
          >
            新增海报
          </Button>,
        ]}
        pagination={{
          showSizeChanger: true,
        }}
        request={async (params) => {
          return await getList(params);
        }}
        loading={loading}
        columns={calcColumns({ operate })}
      />

      <Modal
        open={open}
        title={titleType ? "编辑海报" : "新建海报"}
        forceRender
        onCancel={() => setOpen(!open)}
        width="60%"
        footer={
          <Space>
            <Button onClick={() => setOpen(false)}>取消</Button>
            <Button onClick={submitForm} loading={loading} type="primary">
              确定
            </Button>
          </Space>
        }
      >
        <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }}>
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>
          <Form.Item
            label="上传内容"
            name="imgUrl"
            rules={[{ required: true, message: "上传内容不能为空" }]}
          >
            {postImg ? (
              <div className={styles.avatar_box}>
                <Image width={90} height={160} src={postImg} />
                <a
                  onClick={() => {
                    form.setFieldsValue({ imgUrl: "" });
                    setPostImg("");
                  }}
                >
                  <DeleteOutlined
                    style={{ fontSize: "15px", color: "#ffffff" }}
                  />
                </a>
              </div>
            ) : (
              <UploadPreview
                aspect={670 / 1190}
                fileSize={2}
                onSuccess={(e) => {
                  form.setFieldsValue({ imgUrl: e });
                  setPostImg(e);
                }}
              />
            )}
          </Form.Item>
          <p style={{ marginLeft: "94px", marginTop: "-15px" }}>
            图片推荐尺寸：670x1190px; 大小建议：2M以内;
          </p>
          {/* <Form.Item
            label='上传内容'
            name='type'
            rules={[{required: true, message: 'Please input your username!'}]}
          >
            <Radio.Group>
              <Radio value={1}>满减劵</Radio>
              <Radio value={2}>抵用券</Radio>
            </Radio.Group>
          </Form.Item> */}

          <Form.Item
            label="海报名称"
            name="name"
            rules={[
              { required: true, message: "请输入海报名称,长度不超过20个字" },
            ]}
          >
            <Input maxLength={20} placeholder="请输入海报名称" showCount />
          </Form.Item>

          {/* <Form.Item
            label="所属场馆"
            name="venueId"
            rules={[{ required: true, message: "请选择所属场馆" }]}
          >
            <Select>
              {venueArr.map((v) => (
                <Select.Option value={v.id}>{v.venueName}</Select.Option>
              ))}
            </Select>
          </Form.Item> */}
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default connect((state) => ({
  ...state[namespace],
  submitLoading: state.loading.effects[`${namespace}/submitItem`],
}))(Page);
